"use client"

import React, { useState, useRef, useEffect } from "react"
import { motion } from "framer-motion"
import { X, Minus, Square } from "lucide-react"
import { cn } from "@/lib/utils"

interface DraggableWindowProps {
  title: string
  children: React.ReactNode
  className?: string
  defaultPosition?: { x: number; y: number }
  onClose?: () => void
}

export function DraggableWindow({
  title,
  children,
  className,
  defaultPosition = { x: 50, y: 50 },
  onClose,
}: DraggableWindowProps) {
  const [isDragging, setIsDragging] = useState(false)
  const [position, setPosition] = useState(defaultPosition)
  const [isMaximized, setIsMaximized] = useState(false)
  const [windowSize, setWindowSize] = useState({ width: 800, height: 600 })
  const [prevSize, setPrevSize] = useState({ width: 800, height: 600 })
  const [prevPosition, setPrevPosition] = useState(defaultPosition)
  
  const constraintsRef = useRef<HTMLDivElement>(null)
  const headerRef = useRef<HTMLDivElement>(null)

  // Handle window resize
  useEffect(() => {
    const handleResize = () => {
      if (isMaximized) {
        setWindowSize({
          width: window.innerWidth,
          height: window.innerHeight - 40, // Leave some space at the bottom
        })
      }
    }

    window.addEventListener("resize", handleResize)
    return () => window.removeEventListener("resize", handleResize)
  }, [isMaximized])

  const handleMaximize = () => {
    if (!isMaximized) {
      // Save current position and size before maximizing
      setPrevPosition(position)
      setPrevSize(windowSize)
      
      // Maximize
      setPosition({ x: 0, y: 0 })
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight - 40,
      })
      setIsMaximized(true)
    } else {
      // Restore previous position and size
      setPosition(prevPosition)
      setWindowSize(prevSize)
      setIsMaximized(false)
    }
  }

  const handleMinimize = () => {
    // In a real app, this would minimize the window to the taskbar
    // For this demo, we'll just make it smaller
    if (!isMaximized) {
      setWindowSize({ width: 400, height: 300 })
    }
  }

  return (
    <div ref={constraintsRef} className="fixed inset-0 overflow-hidden pointer-events-none">
      <motion.div
        drag={!isMaximized}
        dragMomentum={false}
        dragListener={false}
        dragElastic={0}
        dragConstraints={constraintsRef}
        dragControls={undefined}
        onDragStart={() => setIsDragging(true)}
        onDragEnd={() => setIsDragging(false)}
        style={{ 
          width: windowSize.width, 
          height: windowSize.height,
          x: position.x,
          y: position.y,
        }}
        className={cn(
          "absolute bg-paint-window border border-paint-border rounded shadow-lg pointer-events-auto",
          className
        )}
      >
        {/* Window header/title bar */}
        <motion.div
          ref={headerRef}
          className="flex items-center justify-between px-4 py-2 bg-paint-toolbar text-foreground border-b border-paint-border cursor-move"
          onPointerDown={(e) => {
            if (!isMaximized && headerRef.current && !e.defaultPrevented) {
              // @ts-ignore - framer-motion types are not complete
              headerRef.current._dragControls?.start(e)
            }
          }}
        >
          <div className="font-medium truncate">{title}</div>
          <div className="flex items-center space-x-2">
            <button
              onClick={handleMinimize}
              className="p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded"
            >
              <Minus size={16} />
            </button>
            <button
              onClick={handleMaximize}
              className="p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded"
            >
              <Square size={16} />
            </button>
            <button
              onClick={onClose}
              className="p-1 hover:bg-red-500 hover:text-white rounded"
            >
              <X size={16} />
            </button>
          </div>
        </motion.div>
        
        {/* Window content */}
        <div className="h-[calc(100%-40px)] overflow-hidden">
          {children}
        </div>
      </motion.div>
    </div>
  )
}